package scatter.func.rest.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import scatter.common.LoginUser;
import scatter.common.rest.controller.SuperController;
import scatter.common.rest.exception.BusinessDataNotFoundException;
import scatter.func.pojo.po.Func;
import scatter.func.pojo.po.FuncGroup;
import scatter.func.pojo.vo.FuncGroupVo;
import scatter.func.rest.FuncConfiguration;
import scatter.func.rest.login.FuncLoginService;
import scatter.func.rest.mapstruct.FuncGroupMapStruct;
import scatter.func.rest.service.IFuncGroupService;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 功能组表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2020-12-07
 */
@RestController
@RequestMapping(FuncConfiguration.CONTROLLER_BASE_PATH + "/func-group/login")
@Api(tags = "功能分组,登录相关")
public class FuncGroupLoginController extends SuperController {

    @Autowired
    private IFuncGroupService iFuncGroupService;

    @Autowired(required = false)
    private FuncLoginService funcLoginService;

    @ApiOperation("当前登录用户的功能组")
    @PreAuthorize("hasAuthority('user')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    public List<FuncGroupVo> getList(@ApiIgnore LoginUser loginUser) {
        if (loginUser.getIsSuperAdmin()) {
            List<FuncGroup> list = iFuncGroupService.list();
            if (isEmpty(list)) {
                throw new BusinessDataNotFoundException(true);
            }
            return FuncGroupMapStruct.INSTANCE.posToVos(list);
        }
        if (funcLoginService == null) {
            throw new BusinessDataNotFoundException(true);
        }
        List<Func> funcs = funcLoginService.retrieveFuncsByUserId(loginUser.getId());
        if (isEmpty(funcs)) {
            throw new BusinessDataNotFoundException(true);
        }
        List<String> groupIds = funcs.stream().map(Func::getFuncGroupId).collect(Collectors.toList());
        if (isEmpty(groupIds)) {
            throw new BusinessDataNotFoundException(true);
        }
        List<FuncGroup> funcGroups = iFuncGroupService.listByIds(groupIds);
        if (isEmpty(funcGroups)) {
            throw new BusinessDataNotFoundException(true);
        }

        return FuncGroupMapStruct.INSTANCE.posToVos(funcGroups);
    }
}
